import { intl } from '@/utils';
import { Button, DataGrid, LoadIndicator, Popup, TreeView } from 'devextreme-react';
import notify from 'devextreme/ui/notify';
import moment from 'moment';
import React, { useCallback, useImperativeHandle, useRef, useState } from 'react';
import * as ReactDOMClient from 'react-dom/client';
import { useModel } from 'umi';
import { CpasIcon, DevPopup, LayoutB } from '~/public/cpas-ui';
import AntTabs from '~/public/cpas-ui/components-ui/ant-components/AntTab';
import { postFetchData } from '../service';
import SetClassiFicationAuto from './SetClassiFication';
import './tabs.less';

const SetClassiFication: React.FC<any> = React.forwardRef((props: any, ref) => {
  const { initialState } = useModel('@@initialState');
  const { dbname } = initialState?.curPart as API.CurPart;
  const { username } = initialState?.curUser as API.CurUser;
  const { width, addData, isQC, DataId, refresh, setNbwltjData } = props;

  //const Divstyle: React.CSSProperties = { display: 'flex', alignItems: "center", justifyContent: "center", marginRight: '10px' };
  const [openVisible111111, setOpenVisibleLoad] = useState<boolean>(false);

  const diaParams = useRef<any>();
  const displayName = useRef<any>(false);
  const devGridRef = useRef<any>();
  const DeletePopupRef = useRef<any>();
  const SetReclassiFiedItemRef = useRef<any>();
  const subjectlist = useRef<any>();

  // const [state,setState] = useState<boolean>(false);
  const [visible, setVisible] = useState<boolean>(false);
  const isChange = useRef<boolean>(false);
  const SelectionClickAccountList = useRef<any>([]);
  const [data, SetData] = useState<any[]>([]);
  const [AccountTreeList, setAccountList] = useState<any[]>([]); // 科目
  const [activeKey, setActiveKey] = useState<string>('0');
  const [AccountFilterData, setAccountFilterData] = useState<any[]>([]); // 试算项目
  const updateGuid = useRef<string[]>([]); // 变更的guid
  const treeViewRef = useRef(); // 定义treeview
  const eventsSaveData = useRef<any>([]); // 变更的数据
  const eventsUpdateData = useRef<any>([]); // 变更的数据
  const clickTimeoutRef: any = useRef(null); //双击检测
  const clickCountRef = useRef(0);
  const eventsNewRowKey = useRef<any>([]);
  const ficationTabsData = [
    { code: '0', type: '全部' },
    { code: '1', type: '资产' },
    { code: '2', type: '负债' },
    { code: '3', type: '利润' },
  ];

  const subjectsTabsData = [
    { code: '0', type: '全部' },
    { code: '1', type: '资产' },
    { code: '2', type: '负债' },
    { code: '3', type: '权益' },
    { code: '4', type: '成本' },
    { code: '5', type: '损益' },
  ];

  // 获取树表格数据
  const getSubjectListDatas = async (params: { DataId: any; zhTZQJ: string; type?: string }) => {
    const { DataId, zhTZQJ, type } = params;
    let postData: any = {};
    if (type === '全部') {
      postData = {
        dbName: dbname,
        tableName: `${DataId}_试算平衡`,
        zhTZQJ: zhTZQJ,
      };
    } else {
      postData = {
        dbName: dbname,
        tableName: `${DataId}_试算平衡`,
        zhTZQJ: zhTZQJ,
        type: type,
      };
    }
    const [res] = await Promise.all([postFetchData('designCell.TbItemName', postData)]);
    // debugger
    if (res.ok) {
      console.log(res.data);
      setAccountFilterData(res.data);
    }
  };

  /**
   *  获取科目类型数据
   * @param params
   */
  const getSubjectTypeData = async (params: { DataId: any }) => {
    const { DataId } = params;
    const [res] = await Promise.all([
      postFetchData('account.subject.getDataList', {
        dbname: dbname,
        isHasFZZ: false,
        Data_ID: DataId,
      }),
    ]);

    if (res.ok) {
      subjectlist.current = res.data;
      setAccountList(res.data);
    }
  };

  // 每次点击触发接口事件 进行右侧树渲染和列表的过滤数据展示
  useImperativeHandle(ref, () => ({
    show: async (params: any) => {
      // setOpenVisibleLoad(true);
      diaParams.current = params;
      setVisible(true);
      updateGuid.current = [];

      devGridRef.current.instance.clearSelection();
      SetData(diaParams.current.leftItemList);
      await getSubjectTypeData(params);
      await getSubjectListDatas(params);
      setOpenVisibleLoad(false);
    },

    getCurrentDevSaveData: async () => {
      return eventsSaveData.current;
    },
    getCurrentDevUpdateData: async () => {
      return eventsUpdateData.current;
    },
    clearDevUpdateData: async () => {
      eventsSaveData.current = [];
      eventsUpdateData.current = [];
    },
  }));

  // 点击关闭按钮逻辑
  const onHiding = () => {
    setVisible(false);
    displayName.current = false;
    console.log('刷新表格');
    if (isChange.current) {
      refresh();
    }
  };

  /**
   *
   * @param e 变化通知函数
   */
  const SavedData = async (e: any) => {
    console.log(e);
    if (e.changes.length) {
      const { data } = e.changes[0];
      console.log(updateGuid.current, 'SavedData');
      if (!updateGuid.current.includes(data.guid)) {
        updateGuid.current.push(data.guid);
      }
    }
  };

  /**
   * 点击选择框
   */

  const onSelectionClickAccountList = (e: any) => {
    SelectionClickAccountList.current = e.selectedRowsData;
  };

  /**
   * 批量设置完成通知函数
   */

  const buthUpdate = (e: []) => {
    //SelectionClickAccountList.current
    // 修改原来选中的记录的科目可项目
    SelectionClickAccountList.current.forEach((ee: any) => {
      if (!updateGuid.current.includes(ee.guid)) {
        updateGuid.current.push(ee.guid);
      }
    });
    // updateGuid.current.concat(SelectionClickAccountList.current.map((id:any)=>id.guid))
    //debugger
    e.forEach((a: any) => {
      SelectionClickAccountList.current.map((b: any) => {
        if (a.DG_NAME === b.DG_NAME) {
          b.itemName = a.itemName;
          b.KMMC = a.KMMC;
        }
      });
    });
    SetData(
      data.map((e: any) => {
        let temp_arr = SelectionClickAccountList.current.filter((c: any) => c.guid === e.guid);
        if (temp_arr.length) {
          return temp_arr[0];
        } else {
          return e;
        }
      }),
    );
  };
  const columns = [
    {
      dataField: 'related',
      dataType: 'string',
      caption: '关联方',
      width: 180,
      // alignment: "left",
      allowEditing: false,
      allowUpdating: false,
      validationRules: [
        // {
        //     type: 'required',
        //     message:'关联方是必填项',
        //     trim:true
        // }
      ],
    },

    {
      dataField: 'itemName',
      dataType: 'string',
      caption: '试算项目名称 *',
      width: 150,
      // alignment: "left",
      allowEditing: false,
      allowUpdating: false,
      validationRules: [
        {
          type: 'required',
          message: '试算项目是必填项',
          trim: true,
        },
      ],
    },
    {
      dataField: 'from_type',
      dataType: 'string',
      caption: '来源',
      width: 180,
      // alignment: "left",
      allowEditing: false,
      allowUpdating: false,
      customizeText: (cellInfo: any) => {
        if (cellInfo.value) {
          return cellInfo.value;
        } else {
          return '手动添加';
        }
      },
    },

    {
      dataField: 'KMMC',
      dataType: 'string',
      caption: '科目名称',
      width: 130,
      // alignment: "left",
      allowEditing: true,
      allowUpdating: true,
      cellTemplate: (cell: any, data: any) => {
        //console.log(data, '@@@',cell);
        return ReactDOMClient.createRoot(cell).render(
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <span style={{ marginLeft: '10%' }}>{data.displayValue}</span>
            <span style={{ marginRight: '10px' }}>
              {/* 点击 清空 */}
              <CpasIcon
                type="icon-chexiao"
                onClick={async () => {
                  DeletePopupRef.current.show({
                    title: '提示',
                    okCallback: async () => {
                      await devGridRef.current.instance.cellValue(
                        displayName.current.rowIndex,
                        'KMMC',
                        '',
                      );
                      await devGridRef.current.instance.saveEditData();
                      // devGridRef.current.instance.cellValue(displayName.current.rowIndex, 'CFLNo', "");
                    },
                  });
                }}
              />
            </span>
          </div>,
        );
      },
    },
    {
      dataField: 'DG_NAME',
      dataType: 'string',
      caption: '底稿表页名称 *',
      width: 180,
      // alignment: "left",
      allowEditing: false,
      allowUpdating: false,
    },
    {
      dataField: 'KXXZ',
      dataType: 'string',
      caption: '款项性质',
      width: 180,
      // alignment: "left",
      allowEditing: false,
      allowUpdating: false,
    },
  ];
  // 右侧 切换方法
  /**
   * 获取项目
   * @param r
   * @returns
   */
  const getSubjectListData = async (r: string) => {
    // console.log(r)
    await getSubjectListDatas({ type: r, DataId: DataId, zhTZQJ: isQC });
  };
  /**
   * 项目点击
   */
  const AccountTabsClick = useCallback(
    async (r: any) => {
      setActiveKey(r);
      // console.log(r)
      ficationTabsData.map(async (item: any) => {
        if (r === item.code) {
          await getSubjectListData(item.type);
        }
      });
    },
    [ficationTabsData],
  );

  const batchSet = () => {
    if (!SelectionClickAccountList.current.length) {
      return notify('请勾选要设置的记录', 'warning', 2000);
    }
    let leftItemList = Array.from(
      new Set(SelectionClickAccountList.current?.map((item: any) => item.DG_NAME)),
    );
    if (leftItemList[0]) {
      SetReclassiFiedItemRef.current.show({
        isok: buthUpdate,
        leftItemList: diaParams.current.Sys_AuditTableName.filter((a: any) =>
          leftItemList.includes(a.StandardSheetName),
        ).map((b: any) => {
          return { DG_NAME: b.StandardSheetName, KMMC: b.KMMC, itemName: b.ReportItemName };
        }),
        DataId: diaParams.current?.DataId,
      });
    } else {
      return notify('手动添加的无法批量自动对应', 'warning', 2000);
    }
  };

  /**
   *
   * @param r 科目点击
   */
  const subjectTabsClick = async (r: any) => {
    setActiveKey(r);
    subjectsTabsData.map(async (item: any) => {
      if (r === item.code) {
        // debugger
        if (r === '0') {
          setAccountList(subjectlist.current);
        } else {
          setAccountList(
            subjectlist.current.filter((it: any) => {
              return it.KMLX && it.KMLX.includes(item.type);
            }),
          );
        }
      }
    });
  };

  function leftContainer() {
    return (
      <div style={{ width: '98%', height: 'calc(100vh - 290px)' }}>
        <DataGrid
          className="grid_Style"
          ref={devGridRef}
          // id="GUID"
          focusedRowEnabled={true}
          hoverStateEnabled={true}
          dataSource={data}
          width="100%"
          height="100%"
          keyExpr="guid"
          columns={columns}
          selection={{
            mode: 'multiple',
            selectAllMode: 'allPages',
            showCheckBoxesMode: 'always',
          }}
          showBorders={true}
          showRowLines={true}
          showColumnLines={true}
          allowColumnResizing={true}
          columnResizingMode="widget"
          headerFilter={{ visible: false }}
          filterPanel={{ visible: false }}
          filterRow={{ visible: false }}
          paging={{
            enabled: false,
          }}
          editing={{
            allowAdding: false,
            allowUpdating: true,
            allowDeleting: false,
            mode: 'cell',
          }}
          onSelectionChanged={onSelectionClickAccountList}
          onSaved={SavedData}
          onCellClick={(res: any) => {
            console.log(res, 'res.rowIndex----');
            displayName.current = res;
          }}
          group={'treeGrid'}
          pages={{
            displayMode: 'compact',
            visible: true,
            showNavigationButtons: true,
            showPageSizeSelector: true,
          }}
          treeDomId={'shareTreeDom'}
        ></DataGrid>
      </div>
    );
  }
  const refreshSubject = (r: boolean) => {
    if (r) {
      getSubjectTypeData(diaParams.current);
      getSubjectListDatas(diaParams.current);
    }
  };

  /**
   * 试算项目
   * @param e
   * @returns
   */
  const onItemClick = async (e: any) => {
    //    debugger
    clickCountRef.current += 1;

    // 如果有计时器在运行，清除它
    if (clickTimeoutRef.current) {
      clearTimeout(clickTimeoutRef.current);
    }
    if (clickCountRef.current === 2) {
      clickCountRef.current = 0; // 重置点击计数
      console.log('li', '2222', displayName.current);
      if (displayName.current !== false) {
        if (displayName.current.rowIndex >= 0) {
          // if(e.level === 66 )
          devGridRef.current.instance.cellValue(
            displayName.current.rowIndex,
            'itemName',
            e.itemData.itemName,
          );
          devGridRef.current.instance.saveEditData();
          // devGridRef.current.instance.cellValue(displayName.current.rowIndex, 'itemName',  e.code);
        }
        return {};
      } else {
        notify('请先选择左侧试算项目', 'warning', 2000);
      }
    }
    // 设置计时器，500ms后重置点击计数
    clickTimeoutRef.current = setTimeout(() => {
      clickCountRef.current = 0;
    }, 500);
  };

  /**
   *  科目
   * @param e
   *
   *
   *  */
  const onSubjustClick = async (e: any) => {
    clickCountRef.current += 1;
    // 如果有计时器在运行，清除它
    if (clickTimeoutRef.current) {
      clearTimeout(clickTimeoutRef.current);
    }
    if (clickCountRef.current === 2) {
      clickCountRef.current = 0; // 重置点击计数
      console.log('li', '2 km222', displayName.current, e.itemData.displayName);
      if (displayName.current !== false) {
        if (displayName.current.rowIndex >= 0) {
          // if(e.level === 66 )
          // debugger
          devGridRef.current.instance.cellValue(
            displayName.current.rowIndex,
            'KMMC',
            e.itemData.displayName,
          );
          await devGridRef.current.instance.saveEditData();
          console.log('wwwwwwww,', displayName.current.rowIndex);
          // devGridRef.current.instance.cellValue(displayName.current.rowIndex, 'CFLNo', e.level === 66 ? e.YSKMBH : e.code);
        }
        return {};
      } else {
        notify('请先选择左侧科目', 'warning', 2000);
      }
    }

    // 设置计时器，500ms后重置点击计数
    clickTimeoutRef.current = setTimeout(() => {
      clickCountRef.current = 0;
    }, 500);
  };

  function rightContainer() {
    return (
      <>
        <Button
          style={{
            position: 'absolute',
            right: '37px',
            zIndex: '1',
          }}
          render={() => <CpasIcon type="icon-refresh" fontSize={16} />}
          onClick={async () => {
            setOpenVisibleLoad(true);
            await refreshSubject(true);
            setActiveKey('0');
            setOpenVisibleLoad(false);
          }}
        />

        <AntTabs style={{ height: '100%', marginLeft: '10px' }}>
          <AntTabs.TabPane tab="试算列表" key="1" style={{ background: '#fff' }}>
            <AntTabs
              activeKey={activeKey}
              tabPosition={'right'}
              className="changeTasHeightBox"
              onChange={AccountTabsClick}
            >
              {ficationTabsData.map((item: any) => {
                return (
                  <AntTabs.TabPane tab={item.type} key={item.code}>
                    <TreeView
                      id="treeview"
                      width={'100%'}
                      height={'calc(100vh - 350px)'}
                      dataStructure="plain"
                      ref={treeViewRef}
                      // dataSource={AccountFilterData}
                      items={AccountFilterData}
                      searchMode="contains"
                      displayExpr="itemName"
                      // selectByClick={true}
                      searchEnabled={true}
                      virtualModeEnabled={true}
                      onItemClick={onItemClick}
                      // onDoubleClick={onItemClick}
                      // onSelectionChanged={onItemClick}
                    />
                  </AntTabs.TabPane>
                );
              })}
            </AntTabs>
          </AntTabs.TabPane>
          <AntTabs.TabPane tab="科目列表" key="2">
            <AntTabs
              activeKey={activeKey}
              tabPosition={'right'}
              className="changeTasHeightBox"
              onChange={subjectTabsClick}
            >
              {subjectsTabsData.map((item: any) => {
                return (
                  <AntTabs.TabPane tab={item.type} key={item.code}>
                    <TreeView
                      id="treeViewTest"
                      height={'calc(100vh - 350px)'}
                      // ref={devTreeRef}
                      selectionMode="single"
                      selectByClick={true}
                      items={AccountTreeList}
                      dataStructure="plain"
                      searchMode="contains"
                      displayExpr="displayName"
                      parentIdExpr="PID"
                      keyExpr="ID"
                      rootValue="0"
                      searchEnabled={true}
                      onItemClick={onSubjustClick}
                      // onItemContextMenu={treeViewItemContextMenu}
                    />
                  </AntTabs.TabPane>
                );
              })}
            </AntTabs>
          </AntTabs.TabPane>
        </AntTabs>
      </>
    );
  }
  const formatDateTime = (dateString: string) => {
    const date = new Date(dateString);

    // 获取年、月、日
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');

    // 获取时、分、秒和毫秒
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    const milliseconds = String(date.getMilliseconds()).padStart(3, '0');

    // 格式化输出
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds.slice(0, 2)}`;
  };
  const OK = async () => {
    // 获取变更的数据更新接口
    await devGridRef.current.instance.saveEditData();

    // 手动添加 和自动获取的，都在这，新增和编辑其实和 之前的逻辑差不多
    // 只有自动获取的可以直接保存
    if (!diaParams.current.db_math) {
      data.forEach((a: any) => {
        console.log(a.guid, 'ok2', updateGuid.current);
        if (updateGuid.current.includes(a.guid)) {
          const baseData = { editDate: moment().format('YYYY-MM-DD HH:mm:ss'), editUser: username };
          if (a.updateFlag) {
            eventsUpdateData.current.push({
              ...baseData,
              rowState: 'update',
              where: { guid: a.guid },
              itemName: a.itemName,
              KMMC: a.KMMC,
            });
          } else {
            eventsSaveData.current.push({
              ...baseData,
              itemName: a.itemName,
              KMMC: a.KMMC,
              guid: a.guid,
              rowState: 'insert',
            });
          }
        }
        // 很少是新增，基本上都是修改，只有新增的时候要搞成新增
      });
      // 渲染
      debugger;
      console.log(eventsSaveData.current, '1ok', eventsUpdateData.current);
      if (eventsSaveData.current.length || eventsUpdateData.current.length) {
        // 调用父组件的set
        //   setNbwltjData((a:any)=>
        console.log([...data], 'ok');
        setNbwltjData([...data]);
      }
    } else {
      let update_data: any[] = [];
      let err_data: any = [];
      data.forEach((a: any) => {
        if (AccountFilterData.filter((e: any) => e.itemName === a.itemName).length) {
          update_data.push(a);
        } else {
          err_data.push(a.related);
        }
      });
      if (err_data.length) {
        notify(
          `关联方： ${err_data.toString()} 中的试算项目和试算项目不匹配，无法导入`,
          'error',
          5000,
        );
      }

      // 执行add
      if (update_data.length) {
        setNbwltjData((a: any) => {
          let copy_arr: any = [...addData({ arr: update_data }, 'Excel'), ...a];
          return [...copy_arr];
        });
      }
    }
    setVisible(false);
  };
  return (
    <div>
      <Popup
        shadingColor="rgba(0, 0, 0, 0)"
        shading={true}
        width={'80vw'}
        height="85%"
        ref={ref}
        dragOutsideBoundary={true}
        resizeEnabled={true}
        visible={visible}
        animation={{ duration: 3 }}
        title="设置对应关系"
        minWidth={500}
        editing={{
          mode: 'cell',
        }}
        {...props}
        // {...size}
        onHiding={onHiding}
        // onResizeEnd={(e) => {
        //     setSize({ width: e.width, height: e.height });
        // }}
        toolbarItems={[
          {
            widget: 'dxButton',
            toolbar: 'bottom',
            location: 'before',
            options: {
              width: 150,
              text: '设置自动对应',
              onClick: () => {
                batchSet();
              },
            },
          },
          {
            widget: 'dxButton',
            toolbar: 'bottom',
            location: 'after',
            options: {
              text: intl('pub.cancel', '关闭'),
              onClick: () => {
                setVisible(false);
                displayName.current = false;
              },
            },
          },
          {
            widget: 'dxButton',
            toolbar: 'bottom',
            location: 'after',
            options: {
              text: intl('pub.ok', '确定'),
              type: 'default',
              onClick: () => OK(),
            },
          },
        ]}
      >
        <div>
          {openVisible111111 && (
            <div
              style={{
                position: 'absolute',
                width: '100%',
                height: '100%',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                opacity: 0.5,
                zIndex: '99999',
                background: '#ddd',
              }}
            >
              <LoadIndicator id="medium-indicator" height={50} width={50} />
            </div>
          )}
          <LayoutB
            rowSize={['10%', '70%', '80%']}
            leftSlot={leftContainer()}
            rightSlot={rightContainer()}
          />
        </div>
      </Popup>
      <SetClassiFicationAuto
        ref={SetReclassiFiedItemRef}
        DataId={diaParams.current?.DataId}
        refresh={() => refresh()}
        closed={() => onHiding()}
      />
      <DevPopup.Default ref={DeletePopupRef} width={80} height={200}>
        {() => {
          return <span>确定要执行此操作吗？</span>;
        }}
      </DevPopup.Default>
    </div>
  );
});

export default React.memo(SetClassiFication);
